#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.
#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import application, cis, command, geography, oms, staker, symbology, unsorted
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
import _mysql as mysql
from django.contrib.auth.models import User

class Condition(models.Model):
    """Condition is a list of Inspections and Condition Reports done on the distribution lines"""
    PriorityImmediateIndicator=models.NullBooleanField(db_column='priorityimmediateindicator', null=True, blank=True)
    PriorityASAPIndicator=models.NullBooleanField(db_column='priorityasapindicator',null=True, blank=True)
    PriorityRoutineIndicator=models.NullBooleanField(db_column='priorityroutineindicator',null=True, blank=True)
    PriorityEverythingFixedMaintenanceOnlyIndicator=models.NullBooleanField(db_column='priorityeverythingfixedmaintenanceonlyindicator',null=True, blank=True)
    PriorityEverythingOkInspectionOnlyIndicator=models.NullBooleanField(db_column='priorityeverythingokinspectiononlyindicator',null=True, blank=True)
    PriorityVegetationNeedsAttentionIndicator=models.NullBooleanField(db_column='priorityvegetationneedsattentionindicator',null=True, blank=True)
    PriorityOutdoorLightingConversionIndicator=models.NullBooleanField(db_column='priorityoutdoorlightingconversionindicator', null=True, blank=True)

    ConditionDepartment=models.ForeignKey('ConditionDepartment', db_column='conditiondepartment')
    PersonReporting=models.TextField(db_column='personreporting', null=True, blank=True)
    DateTimeReported=models.DateTimeField(db_column='datetimereported', null=True, blank=True)
    ReceivedByOperationsIndicator=models.NullBooleanField(db_column='receivedbyoperationsindicator', null=True, blank=True)
    DateTimeReceivedByOperations=models.DateTimeField(db_column='datetimereceivedbyoperations', null=True, blank=True)
    StationIdentifier=models.TextField(db_column='stationidentifier', null=True, blank=True) #Denormalized
    TagNumber=models.TextField(db_column='tagnumber', null=True, blank=True)
    Point=models.PointField(db_column='point', srid=djangoproject.settings.COOPGISSRID, null=True, blank=True)
    Description=models.TextField(db_column='description', null=True, blank=True)  #Description of the Condition

    #indicators to handle movement of outdoorlighting conditions back and forth between COOPIP and COOPGIS
    OutdoorLightBillingWorkStartedIndicator=models.NullBooleanField(db_column='outdoorlightbillingworkstartedindicator', null=True, blank=True)
    OutdoorLightGISPhaseIndicator=models.NullBooleanField(db_column='outdoorlightgisphaseindicator', null=True, blank=True)
    OutdoorLightSendBackToBillingPhaseIndicator=models.NullBooleanField(db_column='outdoorlightsendbacktobillingphaseindicator', null=True, blank=True)
    #outdoor lighting-only fields
    OutdoorLightMapNumber=models.TextField(db_column='outdoorlightmapnumber', null=True, blank=True)
    OutdoorLightMeterNumber=models.TextField(db_column='outdoorlightmeternumber', null=True, blank=True)
    OutdoorLightMeterMapNumber=models.TextField(db_column='outdoorlightmetermapnumber', null=True, blank=True)
    OutdoorLightIdleIndicator=models.NullBooleanField(db_column='outdoorlightidleindicator', null=True, blank=True)
    OutdoorLightCustomerOwnsPoleIndicator=models.NullBooleanField(db_column='outdoorlightcustomerownspoleindicator', null=True, blank=True)
    OutdoorLightCustomerOwnsLightIndicator=models.NullBooleanField(db_column='outdoorlightcustomerownslightindicator', null=True, blank=True)
    OutdoorLightRate=models.ForeignKey('OutdoorLightRate', db_column='outdoorlightrate', null=True, blank=True)
    OutdoorLightProblemCode=models.ForeignKey('OutdoorLightProblemCode', db_column='outdoorlightproblemcode', null=True, blank=True)
    OutdoorLightAdditionalBillingPoleCount=models.IntegerField(db_column='outdoorlightadditionalbillingpolecount', null=True, blank=True)
    #inspection-related fields
    PoleConditionStatus=models.ForeignKey('ConditionStatus', related_name="PoleConditionStatus", db_column='poleconditionstatus')
    GuyAnchorConditionStatus=models.ForeignKey('ConditionStatus', related_name="GuyAnchorConditionStatus", db_column='guyanchorconditionstatus')
    InsulatorConditionStatus=models.ForeignKey('ConditionStatus', related_name="InsulatorConditionStatus", db_column='insulatorconditionstatus')
    ConductorConditionStatus=models.ForeignKey('ConditionStatus', related_name="ConductorConditionStatus", db_column='conductorconditionstatus')
    RightOfWayConditionStatus=models.ForeignKey('ConditionStatus', related_name="RightOfWayConditionStatus", db_column='rightofwayconditionstatus')
    PadMountConditionStatus=models.ForeignKey('ConditionStatus', related_name="PadMountionConditionStatus", db_column='padmountconditionstatus')
    VaultConditionStatus=models.ForeignKey('ConditionStatus', related_name="VaultConditionStatus", db_column='vaultconditionstatus')
    RiserCableConditionStatus=models.ForeignKey('ConditionStatus', related_name="RiserCableConditionStatus", db_column='risercableconditionstatus')

    WorkOrderNumber=models.TextField(db_column='workordernumber',null=True, blank=True)
    WorkRemarks=models.TextField(db_column='workremarks',null=True, blank=True)
    WorkPerformedBy=models.TextField(db_column='workperformedby',null=True, blank=True)
    WorkHours=models.FloatField(db_column='workhours',null=True, blank=True)
    WorkDate=models.DateField(db_column='workdate',null=True, blank=True)
    WorkCompletedIndicator=models.NullBooleanField(db_column='workcompletedindicator',blank=True, null=True)
    WorkNotCompletedIndicator=models.NullBooleanField(db_column='worknotcompletedindicator',blank=True, null=True)
    WorkNotCompletedDescription=models.TextField(db_column='worknotcompleteddescription',null=True, blank=True)
    WorkForeman=models.TextField(db_column='workforeman',null=True, blank=True)
    WorkForemanSignoffIndicator=models.NullBooleanField(db_column='workforemansignoffindicator',null=True, blank=True)
    WorkForemanSignoffDateTime=models.DateTimeField(db_column='workforemansignoffdatetime',null=True, blank=True)
 
    ReviewIndicator=models.NullBooleanField(db_column='reviewindicator',null=True, blank=True)
    ReviewAdditionalAttentionNeededIndicator=models.NullBooleanField(db_column='reviewadditionalattentionneededindicator',null=True, blank=True)
    ReviewComments=models.TextField(db_column='reviewcomments',null=True, blank=True)
    ReviewUserName=models.TextField(db_column='reviewusername',null=True, blank=True)
    ReviewDateTime=models.DateTimeField(db_column='reviewdatetime',null=True, blank=True)

    DeletedIndicator=models.NullBooleanField(db_column='deletedindicator',null=True, blank=True)
    CreateDateTime=models.DateTimeField(db_column='createdatetime',null=True, blank=True)
    CreateUserName=models.TextField(db_column='createusername',null=True, blank=True)
    LastModifyDateTime=models.DateTimeField(db_column='lastmodifydatetime',null=True, blank=True)
    LastModifyUserName=models.TextField(db_column='lastmodifyusername',null=True, blank=True)
    ArchivedIndicator=models.NullBooleanField(db_column='archivedindicator',null=True, blank=True)
    ArchivedUserName=models.TextField(db_column='archivedusername',null=True, blank=True)
    ArchivedDateTime=models.DateTimeField(db_column='archiveddatetime',null=True, blank=True)

    NeedsRetirementIndicator=models.NullBooleanField(db_column='needsretirementindicator', null=True, blank=True)
    RetirementIndicatorModifyUserName=models.TextField(db_column='retirementindicatormodifyusername',null=True, blank=True)
    RetirementIndicatorModifyDateTime=models.DateTimeField(db_column='retirementindicatormodifydatetime',null=True, blank=True)
    RetirementCompleteIndicator=models.NullBooleanField(db_column='retirementcompleteindicator', null=True, blank=True)
    RetirementCompleteUserName=models.TextField(db_column='retirementcompleteusername',null=True, blank=True)
    RetirementCompleteDateTime=models.DateTimeField(db_column='retirementcompletedatetime',null=True, blank=True)

    ResidesOnServerIndicator=models.NullBooleanField(db_column='residesonserverindicator',blank=True, null=True)
    SymbologyYear=models.TextField(db_column='symbologyyear', null=True, blank=True)
    CircuitNumbers=models.TextField(db_column='circuitnumbers', null=True, blank=True)

    objects=models.GeoManager()
    def __unicode__(self):
        return str(self.id)
    class Meta:
        db_table=u'coopgiscondition'
        app_label='djangoproject'
    def GetIndexWhenReverseSorted(self):
        Objects=Condition.objects.all().order_by('-id')
        i = 0
        while(True):
            if(Objects[i] == self):
                return i
            i = i + 1
    def GetCommandidData(self):
        if(self.ResidesOnServerIndicator):
            return self.id, None
        return None, self.GetIndexWhenReverseSorted()
    def GetPriorityString(self):
        if(self.PriorityImmediateIndicator):
            return "IMMEDIATE"
        if(self.PriorityASAPIndicator):
            return "ASAP"
        if(self.PriorityRoutineIndicator):
            return "Routine"
        if(self.PriorityVegetationNeedsAttentionIndicator):
            return "Vegetation"
        if(self.PriorityEverythingFixedMaintenanceOnlyIndicator):
            return "Maintenance"
        if(self.PriorityEverythingOkInspectionOnlyIndicator):
            return "Inspection"
        return "UNKNOWN"
    def GetCurrentAssignment(self):
        try:
            CurrentAssignment=ConditionAssignment.objects.filter(Condition=self).order_by(-'CreateDateTime')[0].Name
        except:
            CurrentAssignment=''
        return CurrentAssignment
    def GetCurrentAssignmentUser(self):
       CurrentAssignment=self.GetCurrentAssignment()
       try:
           currentAssignmentUser=User.objects.filter(username=CurrentAssignment)[0]
       except:
           currentAssignmentUser=None
       return currentAssignmentUser
    
           
class ConditionStatus(models.Model):
    """ConditionStatus is a list of possible conditions that an assembly can be inspected to be in,  "Not Inspected", "Ok", "Not Ok" """
    Name=models.TextField(null=True, blank=True)
    class Meta:
        db_table=u'coopgisconditionstatus'
        app_label='djangoproject'
    def __unicode__(self):
        return self.Name

class ConditionMemberDescriptionHistory(models.Model):
    Condition=models.ForeignKey('Condition', db_column='condition')
    Description=models.TextField(db_column='description',null=True, blank=True)
    CreateDateTime=models.DateTimeField(db_column='createdatetime',null=True, blank=True)
    CreateUserName=models.TextField(db_column='createusername',null=True, blank=True)
    ResidesOnServerIndicator=models.NullBooleanField(db_column='residesonserverindicator',blank=True, null=True)
    class Meta:
        db_table=u'coopgisconditionmemberdescriptionhistory'
        app_label='djangoproject'

class YardLightAssociatedWithMeterNumber(models.Model):
    MeterNumber=models.TextField(db_column='meternumber')
    Quantity=models.IntegerField(db_column='quantity')
    UpdateDateTime=models.DateTimeField(db_column='updatedatetime')
    class Meta:
        db_table=u'coopgisyardlightassociatedwithmeternumber'
        app_label='djangoproject'
    def __unicode__(self):
        return self.Name

class ConditionAssignment(models.Model):
    """ConditionAssignment is a list Assignments that have been made for all conditions (timestamped)"""
    Name=models.CharField(max_length=250)
    Description=models.TextField(null=True, blank=True)
    Condition=models.ForeignKey('Condition')
    CreateDateTime=models.DateTimeField()
    CreateUserName=models.TextField()
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgisconditionassignment'
        app_label='djangoproject'
    def __unicode__(self):
        return self.Name

class ConditionDepartment(models.Model):
    """ConditionDepartment is a list of Departments that a condition can be assigned to"""
    Name=models.CharField(max_length=250)
    Description=models.TextField(null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgisconditiondepartment'
        app_label='djangoproject'
    def __unicode__(self):
        return self.Name

class OutdoorLightConsumerOwnedLightCount(models.Model):
    MeterMapNumber=models.TextField(db_column='metermapnumber', unique=True)
    LightCount=models.IntegerField(db_column='lightcount')
    CreateDateTime=models.DateTimeField(db_column='createdatetime',null=True, blank=True)
    CreateUserName=models.TextField(db_column='createusername',null=True, blank=True)
    LastModifyDateTime=models.DateTimeField(db_column='lastmodifydatetime',null=True, blank=True)
    LastModifyUserName=models.TextField(db_column='lastmodifyusername',null=True, blank=True)
    ResidesOnServerIndicator=models.NullBooleanField(db_column='residesonserverindicator',blank=True, null=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgisoutdoorlightconsumerownedlightcount'
        app_label='djangoproject'

class OutdoorLightRate(models.Model):
    UnitName=models.TextField(db_column='unitname', null=True, blank=True)
    Type=models.TextField(db_column='type', null=True, blank=True)
    Wattage=models.FloatField(db_column='wattage', null=True, blank=True)
    KWH=models.FloatField(db_column='kwh', null=True, blank=True)
    Description=models.TextField(db_column='description', null=True, blank=True)
    ResidesOnServerIndicator=models.NullBooleanField(db_column='residesonserverindicator',blank=True, null=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopgisoutdoorlightrate'
        app_label='djangoproject'
    def __unicode__(self):
        ReturnString=self.Type + ': '  + self.UnitName
        return ReturnString
   
class OutdoorLightProblemCode(models.Model):
    """OutdoorLightProblemCode stores a series of common errors found in the field when creating Conditions for OutdoorLighting
      (being billed at wrong rate, etc); This information is kept for statistical purposes"""
    Name = models.TextField(db_column='name', null=True, blank=True)
    Description = models.TextField(db_column='description', null=True, blank=True)
    class Meta:
        db_table=u'coopgisoutdoorlightproblemcode'
        app_label='djangoproject'
    def __unicode__(self):
        return self.Name


class AMRGISPhaseUpdateLog(models.Model):
    """AMRGISPhaseUpdateLog stores the results of updates to phasing data in the GIS for each meter when changes are made."""  
    OriginatingMeterDCSINumber=models.IntegerField(db_column='originatingmeterdcsinumber', blank=True, null=True)
    DateTime=models.DateTimeField(db_column='datetime', blank=True, null=True)
    Assembly=models.ForeignKey('Assembly', db_column='assembly_id', blank=True, null=True)
    PreviousPhaseCode=models.TextField(db_column='previousphasecode', null=True, blank=True)
    NewPhaseCode=models.TextField(db_column='newphasecode', null=True, blank=True)
    objects=models.GeoManager()
    class Meta:
        db_table=u'coopamrgisphaseupdatelog'
        app_label='djangoproject'
    def __unicode__(self):
        return str(self.id) + ':  ' + str(self.Assemblyid) + '  ' + str(PreviousPhaseCode) + ' --> ' + str(NewPhaseCode)




class ConditionStatusAdmin(admin.ModelAdmin):
    pass

try:
    admin.site.register(ConditionStatus, ConditionStatusAdmin)
except:
   pass


